package com.zsgeek.wisdchain.qutu.view.find;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.zsgeek.wisdchain.qutu.BaseActivity;
import com.zsgeek.wisdchain.qutu.R;
import com.zsgeek.wisdchain.qutu.base.customControl.EmptyRecyclerView;
import com.zsgeek.wisdchain.qutu.base.customControl.LinearLayoutColorDivider;
import com.zsgeek.wisdchain.qutu.base.http.JsonRequest;
import com.zsgeek.wisdchain.qutu.base.http.JsonRequestCallBack;
import com.zsgeek.wisdchain.qutu.base.model.BannerItemDto;
import com.zsgeek.wisdchain.qutu.base.model.GetAdverListModel;
import com.zsgeek.wisdchain.qutu.base.model.QueryCommentModel;
import com.zsgeek.wisdchain.qutu.base.model.StringModel;
import com.zsgeek.wisdchain.qutu.tools.ImageUtils;
import com.zsgeek.wisdchain.qutu.tools.TextUtils;
import com.zsgeek.wisdchain.qutu.tools.ToastHelper;
import com.zsgeek.wisdchain.qutu.tools.UrlPathHelper;
import com.zsgeek.wisdchain.qutu.tools.Utils;
import com.zsgeek.wisdchain.qutu.view.MainActivity;
import com.zsgeek.wisdchain.qutu.view.me.adapter.LoopViewPagerAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 发现--详情
 */
public class FindDetailsActivity extends BaseActivity {
    @BindView(R.id.list_date_emptyView)
    View list_date_emptyView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    EmptyRecyclerView emptyRecyclerView;

    @BindView(R.id.avatar_iv)
    ImageView avatarIv;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.btnRight)
    TextView btnRight;
    @BindView(R.id.title_tc)
    TextView title_tc;
    @BindView(R.id.content_tv)
    TextView contentTv;
    @BindView(R.id.set_comment_tv)
    EditText setCommentTv;
    @BindView(R.id.like_tv)
    TextView likeTv;
    @BindView(R.id.collection_tv)
    TextView collectionTv;
    @BindView(R.id.share_tv)
    TextView shareTv;
    @BindView(R.id.qbpl_tv)
    TextView qbpl_tv;
    @BindView(R.id.bottom_layout)
    LinearLayout bottomLayout;

    @BindView(R.id.home_vp_container)
    ViewPager home_vp_container;
    @BindView(R.id.home_ll_indicators)
    LinearLayout homeLlIndicators;

    private int pageIndex = 1;
    private GetAdverListModel.DataBean dataBean;
    private List<QueryCommentModel.DataBean> dataListBeans = new ArrayList<>();

    private LoopViewPagerAdapter loopViewPagerAdapter;
    private List<BannerItemDto> adsList = new ArrayList<BannerItemDto>();

    @Override
    public int getLayoutId() {
        return R.layout.activity_find_details;
    }

    @Override
    protected void initView() {
        initViewPager();
        emptyRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        emptyRecyclerView.addItemDecoration(new LinearLayoutColorDivider(this.getResources(),
                R.color.color_EAEAEA, R.dimen.one, LinearLayoutManager.VERTICAL));
        emptyRecyclerView.setEmptyView(list_date_emptyView);
        emptyRecyclerView.setAdapter(mAdapter);
//        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
////                startActivityForResult(new Intent(ManagementWalletActivity.this, WalletDetailsActivity.class).putExtra("data", dataListBeans.get(position)), 0x100);
//            }
//        });
        initRefreshLayout();

        setCommentTv.setOnEditorActionListener((v, actionId, event) -> {
//            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                String searchStr = setCommentTv.getText().toString().trim();
                if (TextUtils.isEmpty(searchStr)) {
                    ToastHelper.showToast("说点什么");
                    return true;
                }
                //  业务逻辑
                addComments(1, searchStr);
                //  键盘隐藏
                Utils.CloseInoutDecorView(FindDetailsActivity.this);
            }
            return false;
        });
    }

    @Override
    protected void initDate(Bundle savedInstanceState) {
        dataBean = (GetAdverListModel.DataBean) getIntent().getSerializableExtra("data");
        if (dataBean == null) {
            finish();
        } else {
            toolbarTitle.setText(dataBean.getNickName());
            if (dataBean.getIsGuanzhu() == 2) {
//                btnRight.setText("取消关注");
                btnRight.setVisibility(View.GONE);
            }
            title_tc.setText(dataBean.getLabel());
            contentTv.setText(dataBean.getContent());
            ImageUtils.loadImage(this, dataBean.getHeadImg(), avatarIv);

            collectionTv.setText(dataBean.getCollectNum() + "");
            Drawable collectionTop = dataBean.getIsShoucan() == 2 ? getResources().getDrawable(R.mipmap.love_hollow_red_bg) : getResources().getDrawable(R.mipmap.love_hollow_white_bg);
            collectionTv.setCompoundDrawablesWithIntrinsicBounds(null, collectionTop, null, null);

            likeTv.setText(dataBean.getAgreeNum() + "");
            Drawable liketTop = dataBean.getIsDianzan() == 2 ? getResources().getDrawable(R.mipmap.pentagram_collection_red_bg) : getResources().getDrawable(R.mipmap.pentagram_collection_bg);
            likeTv.setCompoundDrawablesWithIntrinsicBounds(null, liketTop, null, null);

            List<GetAdverListModel.DataBean.ImgesBean> imges = dataBean.getImges();
            if (!TextUtils.isEmpty(imges)) {
                for (int i = 0; i < imges.size(); i++) {
                    adsList.add(new BannerItemDto(imges.get(i).getImgUrl()));
                }
            }
            loopViewPagerAdapter.setList(adsList);

            refreshLayout.autoRefresh();
        }
    }

    private void initViewPager() {
        loopViewPagerAdapter = new LoopViewPagerAdapter(this, home_vp_container, homeLlIndicators);
        home_vp_container.setAdapter(loopViewPagerAdapter);
        loopViewPagerAdapter.setList(adsList);
        home_vp_container.addOnPageChangeListener(loopViewPagerAdapter);
    }


    @OnClick({R.id.btnRight, R.id.like_tv, R.id.collection_tv, R.id.share_tv, R.id.pinglun_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnRight://添加关注
//                if (dataBean.getIsGuanzhu() == 2) {
//                    relationAddComments(2, dataBean.getByAddr());
//                } else
                relationAddComments(1, dataBean.getByAddr());
                break;
            case R.id.like_tv:  //点赞
                if (dataBean.getIsDianzan() != 2) {
//                    addComments(2, dataBean.getByAddr());
//                } else
                    addComments(2, null);
                }
                break;
            case R.id.collection_tv:    //收藏
                if (dataBean.getIsShoucan() != 2) {
//                    addCollections(2);
//                } else
                    addCollections(1);
                }
                break;
            case R.id.share_tv:
                break;
//            case R.id.pinglun_tv://发表评论
//                String comment = setCommentTv.getText().toString().trim();
//                if (TextUtils.isEmpty(comment)) {
//                    ToastHelper.showToast("说点什么");
//                    return;
//                }
//                addComments(1, comment);
//                break;
        }
    }

    private class AllJsonRequestCallBack implements JsonRequestCallBack {
        private int type;

        private AllJsonRequestCallBack(int type) {
            this.type = type;
        }

        @Override
        public void showResult(Object object, String taskId) {
            if (object instanceof StringModel) {
                StringModel dataModel = (StringModel) object;
                if (dataModel.getCode() == 2000) {
                    ToastHelper.showToast((String) dataModel.getData());
                    finish();
                } else {
                    ToastHelper.showToast(dataModel.getMessage());
                }
            } else if (object instanceof QueryCommentModel) {
                QueryCommentModel dataModel = (QueryCommentModel) object;
                stopRefresh();
                if (dataModel.getCode() == 2000) {
                    qbpl_tv.setText(String.format("全部评论：%d", dataModel.getPageQuery().getTotalCount()));
                    List<QueryCommentModel.DataBean> dataBeans = dataModel.getData();
                    if (pageIndex == 1) {
                        dataListBeans.clear();
                    }
                    if (!TextUtils.isEmpty(dataBeans)) {
                        dataListBeans.addAll(dataBeans);
                    }
                    mAdapter.notifyDataSetChanged();
                    if (dataModel.getPageQuery() != null && dataModel.getPageQuery().getTotalPage() <= pageIndex) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    }
                } else {
                    ToastHelper.showToast(dataModel.getMessage());
                }
            }
        }

        @Override
        public void showError(String errorMsg, String taskId) {
            ToastHelper.showToast(errorMsg);
            if (type == 4) {
                stopRefresh();
            }
        }
    }

    /**
     * 添加评论和点赞
     *
     * @param type 类型：1 评论 2 点赞 3 阅读
     * @param info 评论内容(评论填写内容，其他为空)
     */
    private void addComments(int type, String info) {
        new JsonRequest(new AllJsonRequestCallBack(1)).postJson(UrlPathHelper.getAdver() + "user/addComments?addr=" + MainActivity.address
                + "&adverId=" + dataBean.getId() + "&type=" + type + "&info=" + info, true, null, StringModel.class);
    }

    /**
     * 添加关注
     *
     * @param type   类型：1关注 2
     * @param byAddr 博主地址
     */
    private void relationAddComments(int type, String byAddr) {
        new JsonRequest(new AllJsonRequestCallBack(3)).postJson(UrlPathHelper.getAdver() + "relation/addRelation?addr=" + MainActivity.address
                + "&byAddr=" + byAddr + "&type=" + type, true, null, StringModel.class);
    }

    /**
     * 添加收藏
     *
     * @param type
     */
    private void addCollections(int type) {
        new JsonRequest(new AllJsonRequestCallBack(5)).postJson(UrlPathHelper.getAdver() + "collections/addCollections?addr=" + MainActivity.address
                + "&adverId=" + dataBean.getId() + "&type=" + type, true, null, StringModel.class);
    }

    /**
     * 全部消息
     */
    private void getCommentsList() {
//        if (TextUtils.isEmpty(MainActivity.address)) {
//            return;
//        }
//        new JsonRequest(new AllJsonRequestCallBack(4)).postJson(
//                UrlPathHelper.getAdver() + "user/getCommentsList?addr=" + MainActivity.address
//                        + "&pageSize=5&pageIndex=" + pageIndex, true, null, GetCommentsListModel.class);
        new JsonRequest(new AllJsonRequestCallBack(4)).postJson(
                UrlPathHelper.getAdver() + "adver/queryComment?adverId=" + dataBean.getId()
                        + "&pageSize=5&pageIndex=" + pageIndex, true, null, QueryCommentModel.class);
    }

    private BaseQuickAdapter<QueryCommentModel.DataBean, BaseViewHolder> mAdapter =
            new BaseQuickAdapter<QueryCommentModel.DataBean, BaseViewHolder>(R.layout.activity_find_details_item, dataListBeans) {
                @Override
                protected void convert(BaseViewHolder baseViewHolder, final QueryCommentModel.DataBean dataBean) {
                    baseViewHolder.setText(R.id.nick_name_tv, dataBean.getNickName());
                    baseViewHolder.setText(R.id.content_tv, dataBean.getInfo());
                    baseViewHolder.setText(R.id.create_time_tv, dataBean.getCreateTimeFmt());
                    ImageUtils.loadImage(FindDetailsActivity.this, dataBean.getHeadImg(), baseViewHolder.getView(R.id.avatar_iv));
                }
            };

    private void initRefreshLayout() {
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            pageIndex = 1;
            getCommentsList();
        });
        refreshLayout.setOnLoadMoreListener(refreshLayout -> pageIndex++);
    }

    private void stopRefresh() {
        if (pageIndex == 1) {
            refreshLayout.finishRefresh();
            refreshLayout.setEnableLoadMore(true);
        } else {
            refreshLayout.finishLoadMore();
            refreshLayout.setEnableRefresh(true);
        }
    }

}
